/**
 * @param {number[]} org
 * @param {number[][]} seqs
 * @return {boolean}
 */
var sequenceReconstruction = function (org, seqs) {
    if (!seqs.length) return false;
    const len = org.length,
        graph = {},
        inDegrees = new Array(len + 1).fill(0);
    for (let seq of seqs) {
        const n = seq.length - 1;
        for (let i = 0; i < n; i++) {
            const cur = seq[i];
            const next = seq[i + 1];
            if (cur < 1 || next > len) return false;
            if (!graph[cur]) graph[cur] = {};
            if (!graph[cur][next]) {
                graph[cur][next] = true;
                inDegrees[next]++;
            }
        }
        if (seq[n] < 1 || seq[n] > len) return false;
    }

    const queue = [];
    for (let i = 1; i < inDegrees.length; i++) {
        if (inDegrees[i] === 0) {
            if (queue.length === 0 && org[0] === i) {
                queue.push(i);
            } else {
                return false;
            }
        }
    }
    let index = 0;
    while (queue.length === 1) {
        const num = queue.shift();
        if (org[index++] != num) return false;
        for (let next in graph[num]) {
            next = parseInt(next);
            --inDegrees[next];
            if (inDegrees[next] == 0) queue.push(next);
        }
    }
    return index === len;
};
console.log(
    sequenceReconstruction(
        [1, 2, 3],
        [
            [1, 2],
            [1, 3]
        ]
    )
);
console.log(sequenceReconstruction([1, 2, 3], [[1, 2]]));
console.log(
    sequenceReconstruction(
        [1, 2, 3],
        [
            [1, 2],
            [1, 3],
            [2, 3]
        ]
    )
);
console.log(
    sequenceReconstruction(
        [4, 1, 5, 2, 6, 3],
        [
            [5, 2, 6, 3],
            [4, 1, 5, 2]
        ]
    )
);
